import request from '../../util/request.js'
import { createHash } from 'crypto'

const encrypt = (alogrithm, content) => {
  let hash = createHash(alogrithm)
  hash.update(content)
  return hash.digest('hex')
}

/**
 * 
 * @param {Object} options 
 * @returns 
 */
const getSinature = ({accessToken, url}) => {
  return new Promise((resolve, reject) => { 
    if (!accessToken) reject('error accessToken') 
    request(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`)
    .then((result) => {
      if (result.errcode === 0) {
        
        const content = {
          noncestr: 'randomStr',
          jsapi_ticket: result.ticket,
          timestamp: Date.parse(new Date()) / 1000,
          url:decodeURI(url)
        }
        let sortContent = {}
        let sortS = Object.keys(content).sort()
        let str = ''
        sortS.forEach((key,index) => {
          sortContent[key] = content[key];

          // 不要使用qs.stringify序列化网址，会转义网址的特殊字符
          str+= key + '=' + sortContent[key] + (index === sortS.length-1? '' : '&')
        })
        
        
        const signature = encrypt('sha1', str)
        const row = {
          timestamp: content.timestamp,
          noncestr: content.noncestr,
          signature,
          url,
          str
        }
        resolve(row)
      } else {
        reject(result.errmsg)
      }
    }).catch((err) => {
      
      reject(err)
    });
   })
}

export default getSinature